#include "time_xplat.h"

#if _POSIX_C_SOURCE >= 199309L
#include <time.h>
#elif WIN32
#include <windows.h>
#else
#include <time.h>
#include <unistd.h>
static clock_t const initial_clock_value = clock();
#endif


void sleep_ms(int milliseconds) {
	#if _POSIX_C_SOURCE >= 199309L
		struct timespec ts;
		ts.tv_sec = milliseconds / 1000;
		ts.tv_nsec = (milliseconds % 1000) * 1000000;
		nanosleep(&ts, NULL);
	#elif WIN32
		Sleep(milliseconds);
	#else
		usleep(milliseconds * 1000);
	#endif
}


long long get_time_usec() {
	long long time_usec = 0LL;
	#if _POSIX_C_SOURCE >= 199309L
		struct timespec ts;
		clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
		time_usec += ts.tv_sec * 1000 * 1000 + ts.tv_nsec / 1000;
	#elif WIN32
		static char initialized = 0;
		static LARGE_INTEGER counter_frequency;
		LARGE_INTEGER count;

		if (!initialized) {
			QueryPerformanceFrequency(&counter_frequency);
			initialized = 1;
		}
		QueryPerformanceCounter(&count);
		time_usec = count.QuadPart / counter_frequency.QuadPart * 1000 * 1000;
	#else
		// Only 1 second accuracy
		time_usec = time() * 1000 * 1000;
	#endif
	
	return time_usec;
}
